package com.zhang.novel.service.impl;

import com.zhang.novel.core.exception.BusinessException;
import com.zhang.novel.core.utils.Constants;
import com.zhang.novel.core.utils.FileUtil;
import com.zhang.novel.service.FileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;

@Service
@Slf4j
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "pic.save", name = "storage", havingValue = "fastDfs")
public class FastDfsFileServiceImpl implements FileService {

//    private final FastFileStorageClient storageClient;

    @Value("${fdfs.webUrl}")
    private String webUrl;

    @Override
    public String transPic(String picSrc, String picSavePath) {
        // 先将图片保存到本地,获取图片的绝对地址
        File file;
        String filePath = FileUtil.network2Local(picSrc, picSavePath, Constants.LOCAL_PIC_PREFIX);
        // 如果图片是默认图片就不需要上传了，直接返回
        if (filePath.contains(Constants.LOCAL_PIC_PREFIX)) {
            file = new File(picSavePath + filePath);
        } else {
            return filePath;
        }

        // 将图片上传到fastDFS
        try {
            ClientGlobal.initByProperties("config/fastdfs-client.properties");
            System.out.println("network_timeout=" + ClientGlobal.g_network_timeout + "ms");
            System.out.println("charset=" + ClientGlobal.g_charset);
            //创建客户端
            TrackerClient tc = new TrackerClient();
            //连接tracker Server
            TrackerServer ts = tc.getConnection();
            if (ts == null) {
                log.info("getConnection返回为空");
                return "/images/default.gif";
            }
            //获取一个storage server
            StorageServer ss = tc.getStoreStorage(ts);
            if (ss == null) {
                log.info("getStoreStorage返回为空");
                return "/images/default.gif";
            }
            //创建一个storage存储客户端
            StorageClient1 sc1 = new StorageClient1(ts, ss);
            NameValuePair[] meta_list = null; //new NameValuePair[0];
            String item = picSavePath + filePath;
            String fileid;
            fileid = sc1.upload_file1(picSavePath + filePath, "jpg", meta_list);
            //这里额外加上LOCAL_PIC_PREFIX路径，表明该图片是个人资源，而不是爬虫爬取的网络资源，不需要再次进行转换，
            // 实际访问时，再通过nginx的rewite指令来重写路径，去掉LOCAL_PIC_PREFIX
            return webUrl + Constants.LOCAL_PIC_PREFIX + fileid;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            // 删除本地保存的图片
            file.delete();
        }
        return "/images/default.gif";
    }
}
